/**
遇到的问题：
1.防火墙阻止
2.代理软件限制,服务器需要通过代理访问外网，但FTP是内网直接可以访问的.（花费我一下午找该问题- -）
3.解决中文目录问题
支持JAR ：commons-net-3.5.jar
**/
package com.hmall.newskills;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;

import javax.servlet.http.HttpServletResponse;
import javax.swing.text.Document;


public class FTP {
	private static final Logger log = LoggerFactory.getLogger(FTP.class);

    @GetMapping("test")
    @ApiOperation(value = "111")
    public HttpServletResponse test(String url, int port, String username, String password, String localFile, String ftpFile, HttpServletResponse response){
        FtpClient ftp = null;
        ArrayList<String> arFiles = null;
        InputStream is = null;

        FileOutputStream fos = null;
        try {
            //创建地址
            SocketAddress addr = new InetSocketAddress(url, port);
            //连接
            ftp = FtpClient.create();
            ftp.connect(addr);
            //登陆
            ftp.login(username, password.toCharArray());
            ftp.setBinaryType();
            is = ftp.getFileStream(ftpFile);
            File file = new File(localFile);



            byte[] bytes = new byte[1024];
            int i;
            fos = new FileOutputStream(file);
            while((i = is.read(bytes)) != -1){
                fos.write(bytes, 0, i);
            }
            String filename = file.getName();

            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(localFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.close();

            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (FtpProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }


}
 
